package xyz.yjc.websocket.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.yjc.websocket.entity.ClientMessage;
import xyz.yjc.websocket.entity.ServerMessage;


/**
 *
 * @ClassName: WebSocketAction
 * @Description: websocket控制层
 * @author cheng
 * @date 2017年9月27日 下午4:20:58
 */
@Controller
public class WebSocketController {

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  //spring提供的发送消息模板
  @Autowired
  private SimpMessagingTemplate messagingTemplate;


  @Autowired
  private SimpUserRegistry userRegistry;


  @MessageMapping("/sendTest")
  @SendTo("/topic/subscribeTest")
  public ServerMessage sendDemo(ClientMessage message) {
    logger.info("接收到了信息" + message.getName());
    return new ServerMessage("你发送的消息为:" + message.getName());
  }

  @SubscribeMapping("/subscribeTest")
  public ServerMessage sub() {
    logger.info("XXX用户订阅了我。。。");
    return new ServerMessage("感谢你订阅了我。。。");
  }

  @ResponseBody
  @RequestMapping(value = "/templateTest")
  public Object templateTest() {
    logger.info("当前在线人数:" + userRegistry.getUserCount());
    int i = 1;
    for (SimpUser user : userRegistry.getUsers()) {
      logger.info("用户" + i++ + "---" + user);
    }
    //发送消息给指定用户
    messagingTemplate.convertAndSendToUser("test", "/queue/message", new ServerMessage("服务器主动推的数据"));
    return "{}";
  }

  @ResponseBody
  @RequestMapping(value = "/templateTest1")
  public Object templateTest1() {
    logger.info("当前在线人数:" + userRegistry.getUserCount());
    int i = 1;
    for (SimpUser user : userRegistry.getUsers()) {
      logger.info("用户" + i++ + "---" + user);
    }
    //发送消息给指定用户
    messagingTemplate.convertAndSendToUser("test1", "/queue/message", new ServerMessage("服务器主动推的数据"));
    return "{}";
  }

}
